package com.geekyang.rabbitmqapi.quickstart;

import com.rabbitmq.client.*;
import com.rabbitmq.client.QueueingConsumer.Delivery;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author geekyang
 * @date 2018/10/7 23:49
 * 消费者接受信息
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        // 1.创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("39.106.128.50");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 2.从connectionFactory 中获取 connection
        Connection connection = connectionFactory.newConnection();

        // 3.通过connection 创建 channel
        Channel channel = connection.createChannel();

        // 4.声明（创建）队列
        String queueName = "test001";
        channel.queueDeclare(queueName,true, false, false, null);

        // 5.创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        // 6.设置channel
        channel.basicConsume(queueName, true, queueingConsumer);

        while(true){
            // 7.接收消息
            Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消费者消费：" + msg);
            // Envelope envelope = delivery.getEnvelope();
        }

    }

}
